#include "log.h"
#include <QObject>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QDebug>
#include <QStandardItemModel>


Log::Log(QStandardItemModel *model,QObject *parent) : QObject(parent),m_model(model)
{
    filePath = "C:/class123/ggitt/zhangxiao/log.txt";
    QFile file(filePath);
    QFileInfo(file).dir().mkpath(".");

    // 创建并打开文件
    if(file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
    {
        QTextStream out(&file);
        out << "文件创建时间：" << QDateTime::currentDateTime().toString() << "\n";
        file.close();
        qDebug() << "文件创建成功：" << filePath;
    }
    else
    {
        qDebug() << "文件创建失败：" << file.errorString();
    }
    if(m_model)
    {
        m_model->setHorizontalHeaderLabels({"时间", "内容"});
        readfile();
    }
}

void Log::readfile()
{
    QFile file(filePath);
        if(file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QTextStream in(&file);
            while(!in.atEnd())
            {
                QString line = in.readLine();
                QList<QStandardItem*> row;
                row << new QStandardItem(QDateTime::currentDateTime().toString()); // 时间
                row << new QStandardItem(line);                                    // 内容
                m_model->appendRow(row);
            }
            file.close();
        }
}

void Log::writefile(QString message)
{
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        QString logEntry = QString("[%1] %3").arg(timestamp,  message);

        QFile file(filePath);
        if(file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
        {
            QTextStream out(&file);
            out << logEntry << "\n";
            file.close();
        }

        if(m_model)
        {
            QList<QStandardItem*> row;
            row << new QStandardItem(timestamp);
            row << new QStandardItem(message);
             m_model->insertRow(0, row);
        }
}

